package api

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/cgs/app/models"
	"cgs-server/server/cgs/app/models/dto"
	"cgs-server/server/cgs/app/service"
	"cgs-server/server/cgs/app/store"
	"go.mongodb.org/mongo-driver/bson"
	"net/http"
)

type WorksheetGroupHandler struct {
	// srv service
	srv service.Service
	// store
	store store.Factory
}

func NewWorksheetGroupHandler(store store.Factory) *WorksheetGroupHandler {
	return &WorksheetGroupHandler{
		srv:   service.NewService(store),
		store: store,
	}
}

func (wg *WorksheetGroupHandler) Get(w http.ResponseWriter, r *http.Request) {
	groupId := r.FormValue("id")
	if groupId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("group id is required"))
		return
	}
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	group, err := wg.srv.WorksheetGroup().Detail(groupId, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(group))
}

func (wg *WorksheetGroupHandler) Delete(w http.ResponseWriter, r *http.Request) {
	groupId := r.FormValue("id")
	if groupId == "" {
		_, _ = helper.WriteJSON(w, server.Fail("group id is required"))
		return
	}
	newGroupId := r.FormValue("newGroupId")
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	err = wg.srv.WorksheetGroup().Delete(groupId, newGroupId, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK())
}

func (wg *WorksheetGroupHandler) Save(w http.ResponseWriter, r *http.Request) {
	var wsGroup models.WorksheetGroup
	err := helper.ReadRequestBody(&wsGroup, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	err = wg.srv.WorksheetGroup().Save(&wsGroup, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK().WithData(bson.M{"id": wsGroup.GetId()}))
}

func (wg *WorksheetGroupHandler) Update(w http.ResponseWriter, r *http.Request) {
	var wsGroup dto.WorksheetGroup
	err := helper.ReadRequestBody(&wsGroup, w, r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	user, err := base.GetCurrentUser(r)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	err = wg.srv.WorksheetGroup().Update(&wsGroup, user)
	if err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}
	_, _ = helper.WriteJSON(w, server.OK())
}
